package com.cctc.juc.demo.Bitc.Ammap.GThreadLocal.CInheritableThreadLocal;

import lombok.Data;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class InheritableThreadLocalDemo {
    @Data
    private static class Foo {
        private static final AtomicInteger ID = new AtomicInteger(0);
        private int index = 0;
        private int data = 10;

        public Foo() {
            index = ID.getAndIncrement();
        }

        @Override
        public String toString() {
            return index + "@Foo{data=" + data + "}";
        }
    }

    private static final ThreadLocal<Foo> INHERITABLE_THREAD_LOCAL = new InheritableThreadLocal<>();

    public static void main(String[] args) {
        if (INHERITABLE_THREAD_LOCAL.get() == null) {
            INHERITABLE_THREAD_LOCAL.set(new Foo());
        }

        System.out.printf("父线程名称：%s，线程本地变量为：%s%n",
                Thread.currentThread().getName(),
                INHERITABLE_THREAD_LOCAL.get());

        System.out.println("创建子工作线程... ...");

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        new Thread(() -> {
            System.out.printf("当前子工作线程名称：%s，线程本地变量为：%s -> %s%n",
                    Thread.currentThread().getName(),
                    INHERITABLE_THREAD_LOCAL.get(), "InheritableThreadLocal 可以在 [父->子] 线程间传递 inheritableThreadLocalMap 变量。");
        }).start();


        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.printf("父线程名称：%s，线程本地变量为：%s%n",
                Thread.currentThread().getName(),
                INHERITABLE_THREAD_LOCAL.get());

    }


}
